package com.whitehot.klib.http;

import android.text.TextUtils;

import com.whitehot.klib.utils.LogUtil;

import org.json.JSONException;
import java.io.FileNotFoundException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * Created by yutf on 2017/8/23 0023.
 */

public class GlobalErrorInflater
{

    public static ApiException getError(Throwable e)
    {
        LogUtil.e("异常类信息: " + e.toString());
        ApiException ex = null;
        if (e instanceof ConnectException)
        {
            ex = new ApiException(CommonError.HTTP_CONNECTION_ERROR, CommonError.HTTP_ERROR_MSG);
        }else if(e instanceof UnknownHostException)
        {
            ex = new ApiException(CommonError.HTTP_UNKNOWN_HOST_ERROR, CommonError.HTTP_ERROR_MSG);
        }else if(e instanceof SocketTimeoutException)
        {
            ex = new ApiException(CommonError.HTTP_TIMEOUT_ERROR, CommonError.HTTP_ERROR_MSG);
        }else if (e instanceof com.google.gson.JsonParseException ||
                e instanceof JSONException)
        {
            ex = new ApiException(CommonError.INNER_JSON_PARSE_ERROR, CommonError.INNER_ERROR_MSG);
        } else if (e instanceof FileNotFoundException)
        {
            ex = new ApiException(CommonError.INNER_FILE_NOT_FOUND_ERROR, CommonError.INNER_ERROR_MSG);
        } else if (e instanceof IllegalArgumentException)
        {
            ex = new ApiException(CommonError.INNER_FILE_NOT_FOUND_ERROR, CommonError.INNER_ERROR_MSG);
        }else
        {
            if(e instanceof ApiException)
            {
                ApiException apix = (ApiException) e;
                int code = apix.getCode();
                if(code == 404)
                {
                    ex = new ApiException(code, CommonError.HTTP_ERROR);
                }else if(code == 500)
                {
                    ex = new ApiException(code, CommonError.HTTP_ERROR);
                }else
                {
                    if(!TextUtils.isEmpty(apix.getMessage()))
                    {
                        ex = apix;
                    }else
                    {
                        ex = new ApiException(code, CommonError.INNER_ERROR_MSG);
                    }
                }
            }else
            {
                ex = new ApiException(CommonError.UNKNOWN_ERROR, CommonError.INNER_ERROR_MSG);
            }
        }
        return ex;
    }

    public static boolean isNetErr(int code)
    {
        return code == 400
                || code == 500
                || code == CommonError.HTTP_URL_ERROR
                || code == CommonError.HTTP_CONNECTION_ERROR
                || code == CommonError.HTTP_UNKNOWN_HOST_ERROR
                || code == CommonError.HTTP_TIMEOUT_ERROR
                || code == CommonError.SERVER_ERROR_EMPTY
                || code == CommonError.INNER_JSON_PARSE_ERROR;
    }
}
